package com.sniper.springmvc.shiro.filter;

import com.sniper.springmvc.action.admin.AdminLoginController;
import com.sniper.springmvc.utils.HttpRequestUtils;
import org.apache.commons.lang3.text.StrBuilder;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;

/**
 * Created by suzhen on 2017/4/10.
 */
public class SniperAuthenticationFilter extends FormAuthenticationFilter {

    private static final Logger log = LoggerFactory.getLogger(SniperAuthenticationFilter.class);

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (this.isLoginRequest(request, response)) {
            if (this.isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }

                return this.executeLogin(request, response);
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Login page view.");
                }

                return true;
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Attempting to access a path which requires authentication.  Forwarding to the Authentication url [" + this.getLoginUrl() + "]");
            }
            //给url绑定当前url

            HttpServletRequest httpServletRequest = (HttpServletRequest) request;

            if (!HttpRequestUtils.isAjax(httpServletRequest)) {
                StrBuilder builder = new StrBuilder();
                if (httpServletRequest.getContextPath() != null) {
                    //builder.append(httpServletRequest.getContextPath());
                }
                if (httpServletRequest.getServletPath() != null) {
                    builder.append(httpServletRequest.getServletPath());
                }
                if (httpServletRequest.getQueryString() != null) {
                    builder.append("?");
                    builder.append(httpServletRequest.getQueryString());
                }

                httpServletRequest.getSession().setAttribute(AdminLoginController.LOGIN_BACK_URL, URLEncoder.encode(builder.toString(), "utf-8"));
            }

            this.saveRequestAndRedirectToLogin(request, response);
            return false;
        }
    }
}
